require 'proxy_pump/const'
ProxyPump.application do

  get '/proxies' do
    proxies = ProxyPump.cache.all.sort { |a, b| a[:elapsed] <=> b[:elapsed] }
    proxies = proxies.map { |proxy| "#{proxy[:host]}:#{proxy[:port]}" } if params.key?('pure')
    { count: proxies.count, proxies: proxies }
  end

  put '/refresh' do
    ProxyPump.server.crawl_proxies
    'Refresh'
  end

  delete '/clear' do
    ProxyPump.database.execute ProxyPump::Const::EMPTY_PROXIES_SQL
    ProxyPump.cache.clear
    'Clear'
  end

  # /delete?proxy=192.168.0.1:1080
  #
  delete '/delete' do
    proxy = params['proxy']
    host, port = proxy.split ':'
    port = port.to_i
    ProxyPump.database.execute ProxyPump::Const::DELETE_PROXY_SQL, host, port
    ProxyPump.cache.remove(host: host, port: port)
    'Delete'
  end

end
